
#include "land_graphics.h"

#define LAND_2D_CORE

#include "init.h"

static struct {
	LandDraw draw;
}ctx;

typedef struct {
	LandVector rect;
	LandVector color;
}TCmd;

static void
beginDraw(LandScene* scene) {
	LandDraw* draw = &ctx.draw;
	landClearVertex(draw->vertex);
	draw->offset = draw->count = 0;
}

static void
readyDraw(LandScene* scene) {
	landUploadVertex(ctx.draw.vertex);
}

static void
preDraw(LandScene* scene, LandObj* obj) {
	LandShape* shape = (LandShape*)obj;
	LandDraw* draw = &ctx.draw;
	TCmd* cmds;
	unsigned count;
	unsigned drawCount = 0;
	LandVector uv = { 0.f, 0.f, 1.f, 1.f };
	LandVertex* vertex = draw->vertex;
	shape->offset = landGetListTotal(vertex->indexs);
	unsigned offset = landGetListTotal(vertex->points);
	landBeginList(shape->list);
	while (landNextList(shape->list, &cmds, &count)) {
		for (unsigned i = 0; i < count; i++) {
			drawCount += landPushObjRect(
				vertex, &cmds[i].rect, &uv,
				&cmds[i].color, &offset, &obj->transform);
		}
	}
	shape->count = drawCount;
}


static void
drawShape(LandScene* scene, LandObj* obj) {
	LandShape* shape = (LandShape*)obj;
	LandDraw* draw = &ctx.draw;
	if (scene->draw) {
		if (scene->draw == draw) {
			draw->count += shape->count;
			return;
		}
		landDraw(scene->canvas, scene->draw);
	}
	draw->offset = shape->offset;
	draw->count = shape->count;
	draw->view = &scene->view;
	scene->draw = draw;
}

static void
freeShape(LandRef* ref) {
	LandShape* shape = (LandShape*)ref;
}

LAND_2D_API LandShape*
landNewShape() {
	LandShape* shape = landNewExtendObj(sizeof(LandShape), freeShape);
	LandVector color = { 1.f, 1.f, 1.f, 1.f };
	shape->obj.draw = drawShape;
	shape->obj.preDraw = preDraw;
	shape->list = landNewList(sizeof(TCmd), 4);
	return shape;
}

LAND_2D_API void
landClearShape(LandShape* shape) {
	landClearList(shape->list);
}

LAND_2D_API void
landShapeRect(LandShape* shape, LandVector* rect, LandVector* color) {
	TCmd cmd = { *rect, *color };
	landPushList(shape->list, &cmd, 1);
}

void
landInitShapeContext(){
	LandDraw* draw = &ctx.draw;
	draw->depthTest = LAND_DEPTH_TEST_ALWAYS;
	draw->drawType = LAND_DRAW_TRIANGLES;
	draw->shader = landNewStdShader(LAND_STD_SHADER_VERTEX_COLOR);
	draw->vertex = landNewVertex(128);
	landRetainRef(draw->shader);
	landRetainRef(draw->vertex);
	LandSceneMod mod = {
		beginDraw,
		readyDraw,
	};
	landPushSceneMod(&mod);
}